<template>
  <FileUpload
    v-model:url="certificate.picture"
    text="修改凭证"
    :limit="0.8"
    ref="fileUploadRef"
    :height="height"
  />
  <div class="flex">
    <el-upload
      :action="uploadUrl"
      :headers="uploadHeaders"
      accept=".mp3,.m4a"
      :before-upload="beforeAudioUpload"
      :on-success="(response, file, fileList) => { return uploadAudioSuccess(response, file, fileList, 'time') }"
      :limit="99"
      :show-file-list="false"
    >
      <el-button
        type="primary"
        plain
        icon="Upload"
      >上传音频</el-button>
    </el-upload>
    <el-link
      type="primary"
      plain
      size="small"
      icon="Headset"
      v-if="certificate.record"
      class="margin-left-sm"
      style="margin-bottom: 2.5px"
      @click="palyAudioShow()"
    >播放音频</el-link>
    <el-link
      type="danger"
      plain
      size="small"
      icon="Delete"
      v-if="certificate.record"
      class="margin-left-sm"
      style="margin-bottom: 2.5px"
      @click="deleteAudio"
    >删除音频</el-link>
  </div>
  <el-dialog
    width="400px"
    title="音频播放"
    v-model="audioDialogVisible"
  >
    <audio
      controls
      height="100"
      width="300"
      v-if="audioDialogVisible"
    >
      <source :src="certificate.record">
      <embed
        height="50"
        width="300"
        :src="certificate.record"
      >
    </audio>
  </el-dialog>
</template>

<script setup>
import {ref, computed, reactive, watch } from 'vue';
import { ElMessage } from 'element-plus';
import FileUpload from './imgUpload.vue';
import {generateToken} from '@/util/index.ts';

const uploadUrl = '/production/files/upload';
const uploadHeaders = {
  Authorization: generateToken(),
};
const props = defineProps(['height']);
const certificate = reactive({
  picture: '',
  record: ''
})
const audioDialogVisible = ref(false);
const palyAudioShow = () => {
  audioDialogVisible.value = true;
}
const beforeAudioUpload = (file) => {
  const isLt2M = file.size / 1024 / 1024 < 1;
  if (!isLt2M) {
    ElMessage.warning("上传文件大小不能超过 1MB!");
    return false;
  }
  return true;
};
const emit = defineEmits(['emitPicture', 'emitAudio']);
const uploadAudioSuccess = (res, file, fileList, type) => {
  if (res.success) {
    ElMessage.success('上传成功');
    certificate.record = res.data;
    emit('emitAudio', res.data)
  } else {
    ElMessage.warning('上传失败');
  }
};
const deleteAudio = () => {
  certificate.record = ''
  emit('emitAudio', '')
}
watch(() => certificate.picture, (newVal) => {
  emit('emitPicture', newVal);
})
</script>

<style scoped lang="scss"></style>